import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;

import java.net.URI;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class WebSocketClient {

    public static void main(String[] args) throws Exception {
        URI uri = new URI("ws://localhost:8080/websocket/x?a=1");
        final String webSocketUrl = "ws://localhost:8080/websocket/x?a=1";
        WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(
                        uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(65536), handler);
                    }
                });
        Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        new Thread(() -> {
            while (true) {
                String msg = "hello " + System.currentTimeMillis();
                System.out.println("发送消息 " + msg);
                ch.writeAndFlush(new TextWebSocketFrame(msg));
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
            }
        }).start();
        handler.handshakeFuture().sync();
    }

    private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

        private final WebSocketClientHandshaker handshaker;
        private ChannelPromise handshakeFuture;

        public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
            this.handshaker = handshaker;
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) {
            handshakeFuture = ctx.newPromise();
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            handshaker.handshake(ctx.channel());
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) {
            if (!handshaker.isHandshakeComplete()) {
                handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
                if (handshakeFuture != null) {
                    handshakeFuture.setSuccess();
                }
                return;
            }

            if (msg instanceof FullHttpResponse) {
                FullHttpResponse response = (FullHttpResponse) msg;
                throw new IllegalStateException("Unexpected FullHttpResponse: " + response.status());
            } else if (msg instanceof TextWebSocketFrame txt) {
                System.out.println("收到消息：" + txt.text());
            } else if (msg instanceof WebSocketFrame) {
                WebSocketFrame frame = (WebSocketFrame) msg;
                // Handle the WebSocket frame
                System.out.println("收到消息：" + frame);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            if (handshakeFuture != null) {
                handshakeFuture.setFailure(cause);
            }
            ctx.close();
        }

        public ChannelFuture handshakeFuture() {
            return handshakeFuture;
        }
    }

    private static String generateWebSocketKey() {
        SecureRandom random = new SecureRandom();
        byte[] key = new byte[16];
        random.nextBytes(key);
        return Base64.getEncoder().encodeToString(key);
    }
}